<template>
  <div id="users">
    <!-- 导航面板屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible=true">添加</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- scope.row会得到这一行所有的数据 -->
            <!-- {{scope.row.mg_state}} -->
            <el-switch v-model="scope.row.mg_state" @change="userStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserInfo(scope.row.id)"></el-button>
            <!-- 分配按钮 -->
            <el-tooltip content="角色分配" placement="top" :enterable='false'>
              <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="showRolDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>

        </el-table-column>
      </el-table>
      <!-- 分页栏区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="showPage" :page-size="queryInfo.pagesize" layout="total,
       sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!-- 添加用户区域 -->
      <el-dialog title="用户信息" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
        <!-- :model绑定的是表单数据 -->
        <el-form :model="addForm" :rules="addFormRoles" ref="addFFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户区域 -->
      <el-dialog title="提示" :visible.sync="showEditVisible" width="70%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
          <el-form-item label="活动名称">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showEditVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="setRolDialog" width="50%" @close="setRoleDialogClosed">
      <p>当前的用户:{{userInfo.username}}</p>
      <p>当前的角色:{{userInfo.role_name}}</p>
      <p>分配新角色:
        <el-select v-model="selectRoId" placeholder="请选择">
          <el-option v-for="item in rolseLest" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱和手机验证规则，代码是死的，不要改
    // 手机验证规则
    var checkMobile = (rule, value, callback) => {
      const checkemil = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (checkemil.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    // 邮箱验证规则
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      const emailReg = /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/

      if (emailReg.test(value)) {
        return callback()
      }
      return callback(new Error('邮箱格式错误'))
    }
    return {
      queryInfo: {
        // 根据条件参数查询固定的用户信息
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前页显示多少条数据
        pagesize: 3
      },
      // 页码数和用户数据
      total: 0,
      userList: [],
      showPage: [1, 2, 3, 4],
      // 控制弹出用户添加框
      dialogVisible: false,
      // 控制弹出用户修改框
      showEditVisible: false,
      // 用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户信息
      editForm: {},

      // 表单验证规则
      addFormRoles: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户信息表单验证规则
      editFormRules: {
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: checkEmail }],
        mobile: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: checkMobile }]
      },
      // 控制分配角色对话框的显示与隐藏
      setRolDialog: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据
      rolseLest: [],
      // 已选中的角色id值
      selectRoId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 请求接口，获取用户数据
    async getUserList () {
      // 注意请求需要参数的时候必须为params
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) return this.$Message.error('用户获取失败')
      this.userList = res.data.users
      this.total = res.data.total
      console.log(this.userList)
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (pagesize) {
      console.log(pagesize)
      this.queryInfo.pagenum = pagesize
      this.getUserList()
    },
    // 状态变化监听事件,发起接口请求修改数据库用户状态
    async userStatusChange (uestInfo) {
      console.log(uestInfo)
      const { data: res } = await this.$http.put(`users/${uestInfo.id}/state/${uestInfo.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        uestInfo.mg_state = !uestInfo.mg_state
        return this.$Message.error(res.meta.msg)
      } else {
        this.$Message.success(res.meta.msg)
      }
    },
    // 监听添加用户对话框的关闭事件/重置表单
    addDialogClosed () {
      this.$refs.addFFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser () {
      // 对整个表单进行合法验证
      this.$refs.addFFormRef.validate(async valid => {
        if (!valid) return 1
        // 发起添加新用户的api请求
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$Message.error('添加用户失败')
        this.$Message.success(res.meta.msg)
        // 关闭添加用户对话框
        this.dialogVisible = false
        // 重新获取用户数据
        this.getUserList()
      })
    },
    // 点击展示修改用户对话框
    async showEditDialog (id) {
      // 展示对话框
      this.showEditVisible = true
      // console.log(id)
      // 根据id查询数据
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      // 将查询到的数据存到data中
      this.editForm = res.data
    },
    // 监听修改对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮修改用户信息并提交
    editUser () {
      // 对整个表单尽心合法验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return console.log(valid)
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        console.log(res)
        // 成功与否都将结果提示给用户
        if (res.meta.status !== 200) {
          return this.$Message.error(res.meta.msg)
        } else {
          this.$Message.success('修改用户成功')
        }
        // 关闭修改用户对话框
        this.showEditVisible = false
        // 重新获取最新的数据
        this.getUserList()
      })
    },
    // 点击按钮删除用户
    async removeUserInfo (id) {
      // 监听确认删除和取消事件
      const resUser = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        // 一定要使用 catch 接受错误信息，否则后台会报错
      }).catch(err => err)
      // 确认删除返回字符串 confirm
      // 取消删除返回字符串 cancel
      // console.log(resUser)
      if (resUser !== 'confirm') return this.$Message.info('已取消删除')
      // 发起请求接口，根据id删除数据
      const { data: res } = await this.$http.delete('users/' + id, { id: id })
      if (res.meta.status !== 200) return this.$Message.error('删除失败')
      this.$Message.success('删除用户成功')
      console.log(res)
      // 重新发起用户请求，展示最新数据
      this.getUserList()
    },
    // 分配角色对话框
    async showRolDialog (userInfo) {
      this.userInfo = userInfo
      console.log(userInfo)
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      this.rolseLest = res.data
      this.setRolDialog = true
    },
    // 点击按钮，分配角色
    async saveRoleInfo () {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoId })
      if (res.meta.status !== 200) return this.$Message.error('设置角色失败')
      this.$Message.success('设置角色成功')
      this.getUserList()
      this.setRolDialog = false
    },
    // 监听关闭分配角色对话框，重置角色多选框
    setRoleDialogClosed () {
      // 重置用户信息和多选框
      this.selectRoId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
